﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BLL;
using DAL;
using ExpressManagement.Areas.BackSys.ServiceTools;
using DAL.Models;
using System.Text.Json;
using static Newtonsoft.Json.JsonConvert;
using System.Text.Json.Serialization;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc;
using MqTools;
using AutoMapper;
using BLL.Interface;
using Microsoft.Extensions.Caching.Memory;
using ExpressManagement.Areas.BackSys.ServiceTools.Redis;
using Microsoft.EntityFrameworkCore;
using DAL.Models.DTO;

namespace ExpressManagement.Areas.BackSys.Controllers
{
    [Area("BackSys")]
    //[Route("api/[controller]")]
    //[ApiController]
    public class ComplaintController : BaseController
    {
        // GET: Complaint
        // GET: /BackSys/Complaint/
        private readonly IComplaintBagImpl _impl;
        public ComplaintController(IMemoryCache _memoryCache,IComplaintBagImpl _impl, RedisHelper redisHelper, ExpressDBContext _dbContext, IHttpContextAccessor httpContextAccessor, DbContextOptions<ExpressDBContext> _dbContextoptions, IMapper mapper, SignalRSender signalRSender)
            : base(mapper: mapper, signalRSender: signalRSender, httpContextAccessor: httpContextAccessor, _memoryCache: _memoryCache, redisHelper: redisHelper, _dbContext: _dbContext, dbContextOptions: _dbContextoptions)

        {
            //if (_impl == null) _impl = new ComplaintBagImpl();
            this._impl = _impl;

        }



        [HttpGet]
        //[ResponseCache(Duration = 10)]
        public async Task<IActionResult> ChangePage([FromQuery] int page)
        {
     
            //int? page = Convert.ToInt16(Request.Form["pageNum"].ToString().Trim());
            int? rows = GetInt32FromSession("complaintRows");
        
            SetInt32InSession("complaintPage", (int)page);
            string cache = GetCacheFromRedis<string>(EntityComplaint, TypePage, page, LoginType);
            if (!string.IsNullOrEmpty(cache))
            {
                return Json(cache);
            }
            else
            {
                string serializeStr = string.Empty;
                IDictionary<string, string> set = new Dictionary<string, string>();
                if (rows != null)
                {
                    switch (LoginType)
                    {
                        case "用户":
                            UserInfo? detail = GetObjectFromSession<UserInfo>("detail");
                            if (detail != null)
                            {
                                (var userTotalPages, var userComplaints) = _impl.GetList(detail.UserName.Trim(), detail.Phone.Trim(), (int)rows, (int)page);
                                SetInt32InSession("complaintTotalPages", userTotalPages);
                                FillSetAndSaveCache(userTotalPages, SerializeObject(userComplaints), page, set, EntityComplaint, TypePage, LoginType, out serializeStr);
                                return Json(serializeStr);
                            }
                            break;
                        case "管理员":
                        case "快递员":
                            (var totalPages, var complaints) = _impl.GetList((int)rows, (int)page);
                            SetInt32InSession("complaintTotalPages", totalPages);
                            FillSetAndSaveCache(totalPages, SerializeObject(complaints), page, set, EntityComplaint, TypePage, LoginType, out serializeStr);
                            //ViewBag.Complaints = data;
                            return Json(serializeStr);

                        default:
                            break;
                    }
                }
            }
           

         

            return Json(0);
        }

        public async Task<IActionResult> ComplaintManage()
        {
           // int page = 0, rows = 10,totalPages=0;
           // IList<ComplaintBag> data = null;
            
     
           //page = Convert.ToInt16(MySession.GetSession("complaintPage"));
           //rows = Convert.ToInt16(MySession.GetSession("complaintRows"));
       
           // switch (LoginType)
           // {
           //     case "用户":
           //         UserInfo detail = MySession.GetSession_UserInfo("detail");
           //         (totalPages, data) = _impl.GetList(detail.UserName.Trim(), detail.Phone.Trim(), rows, page);
           //         MySession.WriteSession("complaintTotalPages", totalPages);
           //         ViewBag.ComplaintBags = data;
           //         return PartialView();
           //     case "管理员":
           //     case "快递员":
           //         (totalPages, data) = _impl.GetList(rows, page);
           //         MySession.WriteSession("complaintTotalPages", totalPages);
           //         ViewBag.ComplaintBags = data;
           //         return PartialView();
           //     default:
           //         break;
           // }


            //return PartialView(_impl.GetList());
            return PartialView();

        }
        public async Task<IActionResult> List()
        {
            int page = 1;
            if (!string.IsNullOrWhiteSpace(Request.Form["complaintPage"]))
            {
                if (int.TryParse(Request.Form["complaintPage"], out page))
                {
                    if (page < 1)
                    {
                        page = 1;
                    }
                };
            }
            int rows = 10;
            if (!string.IsNullOrWhiteSpace(Request.Form["complaintRows"]))
            {
                if (int.TryParse(Request.Form["complaintRows"], out rows))
                {
                    if (rows < 10)
                    {
                        rows = 10;
                    }
                    else if (rows > 30)
                    {
                        rows = 30;
                    }
                }
            }
            
            return Json(new
            {
                rows = _impl.GetList(rows,page),
                total = _impl.ExistNum
            });
        }


        //
        // GET: /BackSys/Complaint/Details/5
        [HttpGet]
        //[ResponseCache(Duration = 10)]
        public async Task<IActionResult> GetItemByID([FromQuery]int id, [FromQuery] string action)
        {
            Complaint result = _impl.Find(id); 
            if (result != null)
            {
                string seri = SerializeObject(result);              
                return Json(seri);
            }
            return Json(null);
        }

        //
        // GET: /BackSys/Complaint/Create

        public async Task<IActionResult> Create()
        {
            return PartialView();
        }

        //
        // POST: /BackSys/Complaint/Create

        [HttpPost]
        public async Task<IActionResult> Add([FromForm] ComplaintDTO entity)
        {
            Complaint complaint = _mapper.Map<Complaint>(entity);
            //complaint.Id = Convert.ToInt32(Request.Form[["Id"].Trim());
            //var action =Request.Form["Action"];
            //complaint.TrueName =Request.Form["TrueName"].ToString().Trim();
     
            //complaint.Title =Request.Form["Title"].ToString().Trim();
            //complaint.Info =Request.Form["Info"].ToString().Trim();
            //complaint.BagId =Request.Form["BagId"].ToString().Trim();
            //Bag bag = new BagInfoImpl().Find(complaint.BagId);
            //complaint.Phone = Request.Form["Phone"].ToString().Trim();
            //complaint.Idcard = Request.Form["IdCard"].ToString().Trim();
            complaint.SubmitTime = DateTime.Now;
            complaint.ReplyTime = null;
            if (_impl.Add(complaint))
            {
                int? id = GetInt32FromSession("userID");
                if (id != null)
                {
                    await MqSender.SendMessage(new QueueMessage()
                    {
                        Action = QueueMessage.ActionType.COMPLAINT_SUBMIT,
                        Complaint = complaint,
                        User = new UserInfo() { Id = (int)id }
                    }, Resource.CompanyComplaintRoute);
                    return Json(1);
                }
               
            }
            return Json(0);
        }

        [HttpPost]
        public IActionResult GetBagIDs()
        {
            UserInfo?  detail =  GetObjectFromSession<UserInfo>("detail");
            if (detail != null)
            {
                var ids = new BagInfoImpl().GetList(detail.UserName, detail.Phone);
                if (ids == null) return Json(SerializeObject(new List<string>()));
                return Json(SerializeObject(ids[0].Concat(ids[1]).Select(o => o.BagId).ToArray()));
            }
            return Json(SerializeObject(new List<Bag>[] { }));
        }
        public IActionResult ComplaintSubmit()
        {

                switch (LoginType)
                {
                    case "用户":
                        return PartialView();
                    case "管理员":
                    case "快递员":
                        return RedirectToAction("Index","Home");
                    default:
                        break;
                }
         

            return PartialView(new BagInfoImpl().GetList());
        }


        [HttpPost]
        public async Task<IActionResult> Update([FromForm] ComplaintDTO entity)
        {
            //int id = Convert.ToInt32(Request.Form["Id"]);
            //string bagID = Request.Form["BagId"].ToString().Trim();
            Complaint complaint = _mapper.Map<Complaint>(entity);
            if (LoginType.Equals("用户"))
            {
                complaint.Info =Request.Form["Info"];
                if (_impl.Update(complaint.Id, complaint))
                {
                    await MqSender.SendMessage(new QueueMessage()
                    {
                        Action = QueueMessage.ActionType.COMPLAINT_UPDATE,
                        Complaint = complaint,
                        User = new UserInfo() { Id = Convert.ToInt16("userID") }
                    }, Resource.CompanyComplaintRoute);
                    RemoveRedisCacheEntity(EntityComplaint, TypePage, LoginType);
                    return Json(1);
                }
               
            }
            else
            {
                //complaint.ReplyInfo =Request.Form["ReplyInfo"];
                complaint.ReplyTime = DateTime.Now;
                if (_impl.Update(entity.Id, complaint))
                {
                    await MqSender.SendMessage(new QueueMessage()
                    {
                        Action = QueueMessage.ActionType.COMPLAINT_REPLY,
                        Complaint = complaint,
                        User = new UserInfo() { Id=_impl.GetSenderUserIDByBagID(entity.BagId)}
                    }, Resource.CustomerComplaintRoute);
                    RemoveRedisCacheEntity(EntityComplaint, TypePage, LoginType);
                    return Json(1);
                }
               
            }
            //complaint.BagId =Request.Form[.Form["BagId"];
            //complaint.TrueName =Request.Form[.Form["TrueName"];
            //complaint.Phone =Request.Form[.Form["Phone"];
            //complaint.IdCard =Request.Form[.Form["IdCard"];
            //complaint.Title =Request.Form[.Form["Title"];
            //complaint.Info =Request.Form[.Form["Info"];
            //complaint.SubmitTime = DateTime.Now;
            //complaint.AddTime = DateTime.Now;

            return Json(0);

        }

        //
        // GET: /BackSys/Complaint/Delete/5
        [HttpPost]
        public async Task <IActionResult> Delete(int id = 0)
        {

            if (_impl.Delete(id))
            {
                if (LoginType.Equals("用户"))
                {
                    int? userId = GetInt32FromSession("userID");
                    if (userId != null)
                    {
                       await MqSender.SendMessage(

                       new QueueMessage()
                       {
                           Action = QueueMessage.ActionType.COMPLAINT_DELETE,
                           Complaint = new Complaint() { Id = id },
                           User = new UserInfo() { Id = (int)userId }
                       },
                       Resource.CompanyComplaintRoute);
                    }
                }
                else
                {
                   await MqSender.SendMessage(
                     new QueueMessage()
                     {
                         Action = QueueMessage.ActionType.COMPLAINT_DELETE,
                         Complaint = new Complaint() { Id = id },
                         User = new UserInfo() { Id = _impl.GetSenderUserIDByComplaintID(id) }
                     },
                     Resource.CustomerComplaintRoute);
                    await   MqSender.SendMessage(
                     new QueueMessage()
                     {
                         Action = QueueMessage.ActionType.COMPLAINT_DELETE,
                         Complaint = new Complaint() { Id = id },
                         User = new UserInfo() { Id = _impl.GetGetterUserIDByComplaintID(id) }
                     },
                     Resource.CustomerComplaintRoute);
                }

                RemoveRedisCacheEntity(EntityComplaint, TypePage, LoginType);
                return Json(1);
            }


            return Json(0);
        }

        //
      
    }
}